package com.abing.chatRoom.controller;

import com.abing.chatRoom.common.BaseResponse;
import com.abing.chatRoom.common.ErrorCode;
import com.abing.chatRoom.common.ResultUtils;
import com.abing.chatRoom.exception.BusinessException;
import com.abing.chatRoom.model.VO.UserVO;
import com.abing.chatRoom.model.domain.UserTeam;
import com.abing.chatRoom.model.dto.TeamQuery;
import com.abing.chatRoom.model.request.TeamAddRequest;
import com.abing.chatRoom.model.request.TeamJoinRequest;
import com.abing.chatRoom.model.request.TeamQuitRequest;
import com.abing.chatRoom.model.request.TeamUpdateRequest;
import com.abing.chatRoom.service.UserTeamService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.abing.chatRoom.model.VO.TeamUserVO;
import com.abing.chatRoom.model.domain.Team;
import com.abing.chatRoom.model.domain.User;
import com.abing.chatRoom.service.TeamService;
import com.abing.chatRoom.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@CrossOrigin(originPatterns = {"http://localhost"}, allowCredentials = "true", allowedHeaders = {"*"})
@RequestMapping("/team")
@RestController
public class TeamController {
    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    @Resource
    private UserTeamService userTeamService;


    /**
     * 添加队伍
     * @param teamAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request){
        if(teamAddRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest,team);
        long teamId = teamService.addTeam(team, loginUser);

        return ResultUtils.success(teamId);
    }

    /**
     * 删除队伍
     * @param
     * @return
     */
    @GetMapping("/delete")
    public BaseResponse<Boolean>deleteTeam(long teamId, HttpServletRequest request){
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.deleteTeam(teamId, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 更新队伍
     * @param teamUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean>updataTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request){
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean save = teamService.updateTeam(teamUpdateRequest, loginUser);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"插入失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 通过id获取队伍信息
     * @param
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Team>getTeamById(long teamId){
        if(teamId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(teamId);
        if(team==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(team);
    }

    /**
     * 获取队伍列表（特征信息）
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);
        // 1、查询队伍列表
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, isAdmin);
        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getTeamId).collect(Collectors.toList());
        // 2、判断当前用户是否已加入队伍
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getLoginUser(request);
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍 id 集合
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getTeamId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e) {
        }
        // 3、查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        if(teamIdList.isEmpty()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        userTeamJoinQueryWrapper.in("teamId", teamIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setJoinNum(teamIdUserTeamList.getOrDefault(team.getTeamId(), new ArrayList<>()).size()));
        return ResultUtils.success(teamList);
    }
    /**
     * 获取队伍列表页（特征信息）
     * @param teamQuery
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<Team>>ListTeamByPage(TeamQuery teamQuery){
        if(teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery,team);
        Page<Team> page = new Page<Team>(teamQuery.getPageNum(),teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> resultPage = teamService.page(page,queryWrapper);
        return ResultUtils.success(resultPage);
    }

    /**
     * 用户加入队伍
     * @param teamJoinRequest
     * @param request
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Boolean>joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request){
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 退出队伍
     * @param teamQuitRequest
     * @param request
     * @return
     */
    @PostMapping("/quit")
    public  BaseResponse<Boolean>quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request){
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean save = teamService.quitTeam(teamQuitRequest, loginUser);
        return ResultUtils.success(save);
    }

    /**
     * 获取我创建的队伍
     * @param teamQuery
     * @param request
     * @return
     */

    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>>listMyCreateTeams( TeamQuery teamQuery,HttpServletRequest request){
        if(teamQuery ==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",loginUser.getId());
        List<Team> list = teamService.list(queryWrapper);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(loginUser,userVO);
        List<TeamUserVO> teamUserVOList = new ArrayList<>();
        list.forEach(team -> {
            TeamUserVO teamUserVO = new TeamUserVO();
            BeanUtils.copyProperties(team,teamUserVO);
            teamUserVO.setCreateUser(userVO);
            teamUserVOList.add(teamUserVO);
        });
        return ResultUtils.success(teamUserVOList);
    }

    /**
     * 获取我加入的队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>>listMyJoinTeams( TeamQuery teamQuery,HttpServletRequest request){
        if(teamQuery ==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        QueryWrapper<UserTeam>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        //取出不重复的队伍id
        Map<Long, List<UserTeam>> listMap= userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> list = new ArrayList<>(listMap.keySet());
        teamQuery.setIdList(list);
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);
        teamList.forEach(teamUserVO ->{
            teamUserVO.setHasJoin(true);
        });
        return ResultUtils.success(teamList);
    }

    @GetMapping("/{teamId}")
    public BaseResponse<TeamUserVO> getTeamById(@PathVariable Long teamId, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if(loginUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(teamId==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(teamId);
        if(team==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TeamUserVO teamUserVO = new TeamUserVO();
        BeanUtils.copyProperties(team,teamUserVO);
        Long userId = team.getUserId();
        User user = userService.getById(userId);
        UserVO userVo = new UserVO();
        BeanUtils.copyProperties(user,userVo);
        teamUserVO.setCreateUser(userVo);
        return ResultUtils.success(teamUserVO);
    }

    @GetMapping("/hasJoin")
    public BaseResponse hasJoin(Long teamId, HttpServletRequest request) {
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if(loginUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(teamId==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",loginUser.getId());
        queryWrapper.eq("teamId",teamId);
        UserTeam userTeam = userTeamService.getOne(queryWrapper);
        if(userTeam==null){
            return ResultUtils.success(false);
        }
        return ResultUtils.success(true);
    }

}
